package com.googlecode.genie5day;

import android.util.Log;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

/**
 * Created by IntelliJ IDEA.
 * User: Paul
 * Date: Sep 23, 2010
 * Time: 8:36:15 PM
 * To change this template use File | Settings | File Templates.
 */
public class ForecastParser {
    public static String TAG = "ForecastParser";

    public Forecast getForecast(Calendar calFrom) throws Exception {
        Forecast forecast = new Forecast();
        URL url = new URL("http://api.yr.no/weatherapi/locationforecast/1.8/?lat=39.46;lon=-75.70");
        //Set up the initial connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setReadTimeout(10000);
        connection.connect();

        InputSource inputSource = new InputSource(connection.getInputStream());
        TimeZone tz = TimeZone.getTimeZone("GMT");
        calFrom.setTimeZone(tz);
        calFrom.set(Calendar.MINUTE, 0);
        calFrom.set(Calendar.SECOND, 0);
        calFrom.set(Calendar.MILLISECOND, 0);

        XPath xpath = XPathFactory.newInstance().newXPath();
        String dataExpr = "//*";
        Node data = (Node) xpath.evaluate(dataExpr, inputSource, XPathConstants.NODE);

        int hours[] = {0, 3, 6, 9, 12, 15, 18, 21};
        for (int d = 0; d < 5; d++) {
            for (int h : hours) {
                // 2010-09-23T20:00:00Z
                // <time datatype="forecast" from="2010-09-24T03:00:00Z" to="2010-09-24T06:00:00Z">
                calFrom.set(Calendar.HOUR_OF_DAY, h);
                calFrom.getTimeInMillis(); // recompute the time
                Log.i(TAG,"calFrom: " + calFrom);
                Calendar calTo = (Calendar) calFrom.clone();
                calTo.add(Calendar.HOUR_OF_DAY, 3);

                SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:00:ss'Z'");
                fmt.setTimeZone(tz);
                String expression = "/weatherdata/product/time"
                        + "[@from='" + fmt.format(calFrom.getTime()) + "']"
                        + "[@to='" + fmt.format(calTo.getTime()) + "']"
                        + "/location/symbol/@number";
                Log.i(TAG,"expression: " + expression);
                String summary = (String) xpath.evaluate(expression, data, XPathConstants.STRING);
                Log.i(TAG,"summary: " + summary);
                if ("".equals(summary)) {
                    calTo.add(Calendar.HOUR_OF_DAY, 3);
                    expression = "/weatherdata/product/time"
                            + "[@from='" + fmt.format(calFrom.getTime()) + "']"
                            + "[@to='" + fmt.format(calTo.getTime()) + "']"
                            + "/location/symbol/@number";
                    Log.i(TAG,"expression: " + expression);
                    summary = (String) xpath.evaluate(expression, data, XPathConstants.STRING);
                    Log.i(TAG,"summary: " + summary);
                }

                expression = "/weatherdata/product/time"
                        + "[@from='" + fmt.format(calFrom.getTime()) + "']"
                        + "[@to='" + fmt.format(calFrom.getTime()) + "']"
                        + "/location/windDirection/@deg";
                String windDirection = (String) xpath.evaluate(expression, data, XPathConstants.STRING);
                Log.i(TAG,"windDirection: " + windDirection);

                expression = "/weatherdata/product/time"
                        + "[@from='" + fmt.format(calFrom.getTime()) + "']"
                        + "[@to='" + fmt.format(calFrom.getTime()) + "']"
                        + "/location/windSpeed/@mps";
                String windSpeed = (String) xpath.evaluate(expression, data, XPathConstants.STRING);
                Log.i(TAG,"windSpeed: " + windSpeed);

                expression = "/weatherdata/product/time"
                        + "[@from='" + fmt.format(calFrom.getTime()) + "']"
                        + "[@to='" + fmt.format(calFrom.getTime()) + "']"
                        + "/location/temperature /@value";
                String temperature = (String) xpath.evaluate(expression, data, XPathConstants.STRING);
                Log.e(TAG,"temperature: " + temperature);
                if ("".equals(temperature)) {
                    continue;
                }
                ForecastDetail detail = new ForecastDetail();
                detail.setCalendar((Calendar) calFrom.clone());
                detail.setTemp(Double.parseDouble(temperature) * 9 / 5 + 32);
                detail.setWindSpeed(Double.parseDouble(windSpeed) / 2.23693629);
                detail.setWindDirection(Double.parseDouble(windDirection));
                if (!"".equals(summary)) {
                    detail.setSummary(Integer.parseInt(summary));
                    forecast.setForecastDetail(detail.getCalendar(), detail);
                }
            }
            calFrom.add(Calendar.DAY_OF_YEAR, 1);
        }
        return forecast;
    }
}
